#!/bin/bash
CUR_DIR=$(pwd)
TARGET_REPO=$CUR_DIR/../aosp-patches

echo "CUR_DIR=$CUR_DIR"

ALL_PROJECTS_DIRS=$(repo list -p)

for project_dir in $ALL_PROJECTS_DIRS; do
    cd $CUR_DIR/$project_dir
    # 找到所有当前仓库已修改的文件
    MODIFIED_FILES=$(git ls-files --modified)
    # 找出当前仓库中的所有已修改和新添加的文件
    ALL_MODIFIED_FILES=$(git ls-files --modified --others --exclude-standard)
    if  [ -z "$ALL_MODIFIED_FILES" ]; then
        continue
    fi
    TARGET_PROJECT_DIR=$TARGET_REPO/$project_dir
    for file in $MODIFIED_FILES; do
        # 创建目录
        TARGET_FILE_DIR=$TARGET_PROJECT_DIR/$(dirname "$file")
        if [ ! -d "$TARGET_FILE_DIR" ]; then
            mkdir -p $TARGET_FILE_DIR
        fi
        if [ ! -e "$TARGET_PROJECT_DIR/$file" ]; then
            #文件不存在则添加到git仓库
            #备份当前修改的文件
            cp -rf "$file" "${file}_bak"
            #还原修改
            git checkout $file
            cp -rf "$file" "$TARGET_PROJECT_DIR/$file"
            cd $TARGET_PROJECT_DIR
            git add "$file"
            git commit -m "原始文件$(basename $file)"
            cd $CUR_DIR/$project_dir
            mv "${file}_bak" "$file"
        fi
    done

    # 复制修改后的文件到目标仓库
    echo "Modify files in $project_dir is"
    echo "++++++++++++++++++++++++++++"
    for file in $ALL_MODIFIED_FILES; do
        echo "$file"
        TARGET_FILE_DIR=$TARGET_PROJECT_DIR/$(dirname "$file")
        if [ ! -d "$TARGET_FILE_DIR" ]; then
            mkdir -p $TARGET_FILE_DIR
        fi
        cp -rf $file $TARGET_PROJECT_DIR/$file
    done
    echo "++++++++++++++++++++++++++++"
    cd $CUR_DIR/
done 